package com.muqi.app.qlearn.student.ui;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import com.github.mikephil.charting.charts.PieChart;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.Legend.LegendPosition;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.PieData;
import com.github.mikephil.charting.data.PieDataSet;
import com.github.mikephil.charting.formatter.PercentFormatter;
import com.muqi.app.network.http.MyAsyncHttp;
import com.muqi.app.network.http.ParamsUtils;
import com.muqi.app.network.http.ResponseUtils;
import com.muqi.app.network.http.MyAsyncHttp.AsyncCallBackListener;
import com.muqi.app.network.http.MyAsyncHttp.RESULTCODE;
import com.muqi.app.project.contants.NetWorkApi;
import com.muqi.app.project.utils.NumberFormatUtil;
import com.muqi.app.qlearn.modles.ClassRoomCommentStatisticsEntity;
import com.muqi.app.qlearn.modles.CompanyStatisticsInfo;
import com.muqi.app.qlearn.modles.HomeWorkStatisticsInfo;
import com.muqi.app.qlearn.student.BaseStudentActivity;
import com.muqi.app.qlearn.student.R;
import com.muqi.app.user.db.ChildBean;
import com.muqi.app.user.widget.ClubWindow;
import com.muqi.app.user.widget.ClubWindow.ClickClubWindowListener;

import android.graphics.Color;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.TextView;

public class HomeWorkStatisticActivity extends BaseStudentActivity implements
		OnClickListener, ClickClubWindowListener {
	private PieChart mPieChart_homework;
	private PieChart mPieChart_company;
	private TextView tv_title;
	private TextView tv_statis_homework;
	private TextView tv_statis_company;

	private ImageView bt_time;

	private ClubWindow mywindow = null;
	private String timeType = "all";

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_home_work_statistic);
	}

	@Override
	protected void onInit() {
		super.onInit();
		mPieChart_company = (PieChart) findViewById(R.id.statistics_piechart_company);
		mPieChart_homework = (PieChart) findViewById(R.id.statistics_piechart_homework);
		tv_title = (TextView) findViewById(R.id.tv_title);
		bt_time = (ImageView) findViewById(R.id.comment_statistics);
		tv_statis_homework = (TextView) findViewById(R.id.tv_statis_homework);
		tv_statis_company = (TextView) findViewById(R.id.tv_statis_company);
		bt_time.setOnClickListener(this);

	}

	@Override
	protected void onData() {
		super.onData();
		
		tv_title.setText(currentChildName);
		getStatisticsHomeData(timeType);
		getStatisticsCompanyData(timeType);
	}

	/**
	 * 获得统计的数据
	 * 
	 * @param string
	 */
	private void getStatisticsHomeData(String string) {
		HashMap<String, Object> sendMap = new HashMap<String, Object>();
		sendMap.put("token", mSpUtil.getToken());
		sendMap.put("student_id", mSpUtil.getCurrentChildId());
		sendMap.put("type", string);// 默认是0
		String requestUrl = ParamsUtils.buildParams(
				NetWorkApi.GET_HOMEWORK_STATISC, sendMap);
		MyAsyncHttp.get(mContext, requestUrl, new AsyncCallBackListener() {

			@Override
			public void onAsyncCallBack(RESULTCODE resuleCode, String request,
					String result) {
				if (resuleCode == RESULTCODE.SUCCESS) {
					Log.e("===", result);
					ArrayList<HomeWorkStatisticsInfo> infos = ResponseUtils
							.getHomeStatisticsInfos(mContext, result);
					if (infos != null) {
						showChart(mPieChart_homework, infos);
					}

				}

			}

		});
	}

	/**
	 * 获得陪伴的数据
	 * 
	 * @param string
	 */
	private void getStatisticsCompanyData(String string) {
		HashMap<String, Object> sendMap = new HashMap<String, Object>();
		sendMap.put("token", mSpUtil.getToken());
		sendMap.put("student_id", mSpUtil.getCurrentChildId());
		sendMap.put("type", string);// 默认是0
		String requestUrl = ParamsUtils.buildParams(
				NetWorkApi.GET_COMPANY_STATISC, sendMap);
		MyAsyncHttp.get(mContext, requestUrl, new AsyncCallBackListener() {

			@Override
			public void onAsyncCallBack(RESULTCODE resuleCode, String request,
					String result) {
				if (resuleCode == RESULTCODE.SUCCESS) {
					Log.e("===", result + "pei");

					ArrayList<CompanyStatisticsInfo> infos = ResponseUtils
							.getCompanyStatisticsInfos(mContext, result);

					if (infos != null) {
						showChart(mPieChart_company, infos);

					}

				}

			}

		});
	}

	private <T> void showChart(PieChart pieChart, List<T> statisticsList2) {

		pieChart.setHoleColorTransparent(true);
		pieChart.setHoleRadius(0); // 半径
		pieChart.setTransparentCircleRadius(0); // 半透明圈
		pieChart.setDescription("");
		pieChart.setDrawCenterText(false); // 饼状图中间可以添加文字
		pieChart.setDrawHoleEnabled(true);
		pieChart.setRotationAngle(90); // 初始旋转角度
		pieChart.setRotationEnabled(false); // 可以手动旋转
		pieChart.setUsePercentValues(true); // 显示成百分比
		pieChart.setNoDataTextDescription("There is no data");
		// 设置数据
		PieData mPieData = getPieData(statisticsList2);
		pieChart.setData(mPieData);

		// 设置标注的信息
		Legend mLegend = pieChart.getLegend(); // 设置比例图
		mLegend.setPosition(LegendPosition.LEFT_OF_CHART); // 最右边显示
		mLegend.setTextColor(getResources().getColor(R.color.chart_title_color));
		mLegend.setXEntrySpace(7f);
		mLegend.setYEntrySpace(5f);
		mLegend.setYOffset(10);

		pieChart.animateXY(1000, 1000); // 设置动画

	}

	/**
	 * 
	 * @param <T>
	 * @param count
	 *            分成几部分
	 * @param range
	 */

	private <T> PieData getPieData(List<T> statisticsList) {

		ArrayList<String> xValues = new ArrayList<String>(); // xVals用来表示每个饼块上的内容
		ArrayList<Entry> yValues = new ArrayList<Entry>(); // yVals用来表示封装每个饼块的实际数据

		for (int i = 0; i < statisticsList.size(); i++) {
			if (statisticsList.get(i) instanceof HomeWorkStatisticsInfo) {
				Log.e("===", statisticsList.get(i).toString());
				HomeWorkStatisticsInfo info = (HomeWorkStatisticsInfo) statisticsList
						.get(i);
				if (!"0".equals(info.count)) {
					xValues.add(info.hourspan + "点之前");
					yValues.add(new Entry(NumberFormatUtil
							.getFloatFromString(info.count), i));
				}
			} else if (statisticsList.get(i) instanceof CompanyStatisticsInfo) {
				CompanyStatisticsInfo info = (CompanyStatisticsInfo) statisticsList
						.get(i);
				if (!"0".equals(info.count)) {
					if ("n".equals(info.status)) {
						xValues.add("未陪伴");
					} else if ("y".equals(info.status)) {
						xValues.add("陪伴");
					}
					yValues.add(new Entry(NumberFormatUtil
							.getFloatFromString(info.count), i));
				}
			}

		}

		// y轴的集合
		PieDataSet pieDataSet = new PieDataSet(yValues, "");// "Quarterly Revenue 2014"/*显示在比例图上*/);
		if (yValues.size() > 1) {
			pieDataSet.setSliceSpace(5f); // 设置个饼状图之间的距离

		} else {
			pieDataSet.setSliceSpace(0f);
		}

		ArrayList<Integer> colors = new ArrayList<Integer>();

		// 饼图颜色

		colors.add(Color.rgb(37, 197, 85));
		colors.add(Color.rgb(79, 61, 150));
		colors.add(Color.rgb(147, 255, 255));
		colors.add(Color.rgb(89, 134, 198));
		colors.add(Color.rgb(255, 128, 192));
		colors.add(Color.rgb(255, 146, 36));
		pieDataSet.setColors(colors);

		DisplayMetrics metrics = getResources().getDisplayMetrics();
		float px = 5 * (metrics.densityDpi / 160f);
		pieDataSet.setSelectionShift(px); // 选中态多出的长度

		PieData pieData = new PieData(xValues, pieDataSet);

		pieData.setValueFormatter(new PercentFormatter());
		pieData.setValueTextSize(10f);
		pieData.setValueTextColor(getResources().getColor(
				R.color.statis_text_color));

		return pieData;
	}

	@Override
	public void onClick(View arg0) {
		switch (arg0.getId()) {
		case R.id.tv_title:
			showChildrenWindow(arg0);
			break;
		case R.id.comment_statistics:
			if (mywindow == null) {
				mywindow = new ClubWindow(this, this);
			}
			mywindow.showPopupWindow(arg0);
			break;

		default:
			break;
		}
	}

	public void onBack(View v) {
		this.finish();
	}

	@Override
	public void onClickClubWindowListener(int time, String typeName) {
		tv_statis_company.setText(getStringType(typeName) + "家长陪伴统计");
		tv_statis_homework.setText(getStringType(typeName) + "作业完成时刻统计");
		getStatisticsCompanyData(typeName);
		getStatisticsHomeData(typeName);
	}

	/**
	 * 将选择的时间类型转换为汉字
	 * 
	 * @param typeName
	 * @return
	 */
	private String getStringType(String typeName) {
		Log.e("===", typeName);
		String str = "";
		if (("day").equals(typeName)) {
			str = "今天";

		} else if (("week").equals(typeName)) {
			str = "最近一周";

		} else if (("month").equals(typeName)) {
			str = "最近一个月";
		} else if (("year").equals(typeName)) {
			str = "最近一年";
		}

		return str;
	}

	/**
	 * 针对父母 选择相应的学生
	 */
	@Override
	protected void onChoiceChildResult(ChildBean myChild) {
		tv_title.setText(currentChildName);
		getStatisticsCompanyData(timeType);
		getStatisticsHomeData(timeType);
	}

}
